$(document).ready(function() {
    $('#ajaxmsg').click(function(){
        $(this).hide();
    });
    /*======update cart======*/
    $('#updCart').click(function(){
		var quoteId = $('#quoteId-hidden').val();
		updateQuoteData(quoteId);
		updateCart(true);
	});

    //changing quote status
    $('table#quotetable').delegate('.qstatus', 'change', function(){
        var urlwebsite = $('#wsurl-hidden').val();
        var qId = $(this).attr('id').replace('qstat-', '');
        var newStat = $(this).val();
        
        if (newStat.toLowerCase() == 'lost') {
            var postmortem = prompt('Add a short postmortem here. Why did we lose the deal?', '');
        } else {
            var postmortem = false ;
        }
        
        $.ajax({
            type	 : 'post',
            url		 : urlwebsite+'sys/backend_quote/updatestatus/',
            data	 : ({qid:qId, status:newStat, postmortem: postmortem}),
			dataType : 'JSON',
			success  : function(result){
				if(result.error) {
					$('#ajaxmsg').text(result.msg);
				}
				else {
					$('#ajaxmsg').text('Quote status changed').fadeOut('slow');
				}
				$('table#quotetable').dataTable().fnDraw(false);
            },
			beforeSend: function(){
				$('#ajaxmsg').text('Changing quote status. Please wait...').show();
			}
        });
    })
    .delegate('.delquote', 'click', function(){ //removing quote
        if(!confirm('Do you really want to delete this quote? This operation can not be undone.')) {
            return false;
        }
        var urlwebsite = $('#wsurl-hidden').val();
        var qId = $(this).attr('id').replace('qdel-', '');
        
        $.ajax({
            type	 : 'post',
            url		 : urlwebsite+'sys/backend_quote/deletequote/',
            data	 : ({qid:qId}),
			dataType : 'JSON',
            success  : function(result){
                if(result.error) {
                    $('#ajaxmsg').text(result.msg);
                }
                else {
					$('#ajaxmsg').hide();
                }
				$('table#quotetable').dataTable().fnDraw(false);
            },
			beforeSend: function(){
				$('#ajaxmsg').text('Removing quote. Please wait...').show();
			}
        });
    })   
    .delegate('.invoice', 'click', function(event){ // invoice pdf creation
		event.preventDefault()
		var id = parseInt($(this).closest('tr').children('td.quoteid').text());
		$('#dialog_invoice').find('#quote_id').val(id);
		$('#dialog_invoice').dialog("open");
    });

    $('#usercart').find('.itqty').change(function(){
        var id = $(this).attr('id').replace('inptoupdcnt-', '')
        var qty = $(this).val()
        storeChangedParam( $('#usercart'), 'toUpdQty', id, qty )
        blink('#updCart');
    });

    $('#usercart').find('.itprice').change(function(){
        var id = $(this).attr('id').replace('inptoupd-', '')
        var qty = $(this).val()
        storeChangedParam( $('#usercart'), 'toUpdPrice', id, qty )
        blink('#updCart');
    });

    $('#usercart').find('.adminnote').change(function(){
        var id = $(this).attr('id').replace('adminnote-', '')
        var qty = $(this).val()
        storeChangedParam( $('#usercart'), 'adminNotes', id, qty )
        blink('#updCart');
    });

    

})

function blink(jqSelector){
    $(jqSelector)
    .animate({'color':'red'},300).delay(200).animate({'color':'#eee'},300)
    .delay(200).animate({'color':'red'},300).delay(200).animate({'color':'#eee'},300)
    .delay(200).animate({'color':'red'},300).delay(200).animate({'color':'#eee'},300);
}

function updateCart(noReload) {
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    var quoteId = $('#quoteId-hidden').val();
    
    var disclaimer   = trim($('#quote-disclaimer').val());
    var intmsgtext   = $('#intmsgtext').val();
    var mailusertext = $('#mailusertext').val();
    //show message on ajax start
    //only if button 'update cart' pressed
    if ( false !== noReload) {
        $('#ajaxmsg').ajaxStart(function(){
            $(this).text('Updating cart. Please wait...');
            $(this).show();
        })
    }
    //send ajax request
    $.ajax({
		async: false,
        type : 'post',
        url : urlwebsite+'sys/backend_quote/updatecart/',
        data : ({
                qid:cartId,
                toUpdPrice  : json_encode($('#usercart').data('toUpdPrice')),
                toUpdQty    : json_encode($('#usercart').data('toUpdQty')),
                notes       : json_encode($('#usercart').data('adminNotes')),
                disclaimer  : disclaimer,
                intMsgText  : intmsgtext,
                mailUserText: mailusertext,
                quoteId     : quoteId,
                discount    : trim($('#discount').val()),
				discountTaxRate : $('#discount-tax-rate').find('option:selected').index()
            }),
        success: function(){
                //do not reload page if function called from other function
                if ( false !== noReload) window.location.reload();
        },
        error : function() {
        }
    });
}

function replaceOnClick(content) {
    //return content.replace(/Sc.addVariableProductToContent\('([0-9]+)'.*\)/g, 'addProductToCart($1)');
    return content.replace(/Sc.addVariableProductToContent\('([0-9]{1,10})', '.*'\)/g, 'addProductToCart($1)');
}

function addProductToCart(id) {
	var quoteId = $('#quoteId-hidden').val();
	updateQuoteData(quoteId);
    updateCart(false);
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    $('#ajaxmsg').ajaxStart(function(){
        $(this).text('Adding product. Please wait...');
        $(this).show();
    })
    $.ajax({
        type    : 'post',
        url     : urlwebsite+'sys/backend_quote/addproducttocart/',
        data    : ({pid:id, cid: cartId}),
        dataType: 'json',
        success: function(result){
            if(result.error) {
                $('#ajaxmsg').text(result.msg);
            }
            else {
				$('#ajaxmsg').text('Updating. Please wait...')
				$('input,select,textarea').val(''); //reseting elements
                window.location.reload();
			}
        }
    });
}

function updateQuoteData(quoteId) {
    var urlwebsite = $('#wsurl-hidden').val();
    var regEmail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/;
    var quoteMail = trim($('#qupdMail').val());
    var quoteDate = trim($('#qupdDate').val());
    var quoteName = trim($('#qupdName').val());
    
    var shipping = $('#shipping').val();
    if (!$('#same-data-for-shipping').attr('checked')) {
        var shippingData = {
            firstname: trim($('#shipping-firstname').val()),
            lastname: $('#shipping-lastname').val(),
            company: $('#shipping-company').val(),
            email: $('#shipping-email').val(),
            address1: $('#shipping-address1').val(),
            address2: $('#shipping-address2').val(),
            city: $('#shipping-city').val(),
            state: (null !== $('#shipping-state').val() ? $('#shipping-state').val() : ''),
            zip: $('#shipping-zip').val(),
            country: $('#shipping-country').val(),
            phone: $('#shipping-phone').val()
        }
    }
    if (!/^([0-9.]{1,10})$/.test(shipping)) {
        shipping = 0;
    }

    if(quoteMail == '' || !quoteMail.match(regEmail) || quoteDate == '') {
	alert('Please, enter a valid data.');
	return;
    }    

    $('#ajaxmsg').ajaxStart(function(){
        $(this).text('Updating, please wait...');
        $(this).show();
    })
    
    $.ajax({
		async: false,
        type : 'post',
        url : urlwebsite+'sys/backend_quote/updatequoteoncreation/',
        data : ({
            qid : quoteId,
            qMail : quoteMail,
            qDate : quoteDate,
            qName : quoteName,
            qValidUntilDate : $('#qupdValidUntilDate').val(),
            name : $('#cart-quote-name').val(),
            company : $('#cart-quote-company').val(),
            country : $('#cart-quote-country').val(),
            state : $('#cart-quote-state').val() !== null ? $('#cart-quote-state').val() : '',
            city : $('#cart-quote-city').val(),
            zip : $('#cart-quote-zip').val(),
            address1 : $('#cart-quote-address1').val(),
            address2 : $('#cart-quote-address2').val(),
            phone : $('#cart-quote-phone').val(),
            comments : $('#cart-quote-comments').val(),
            shipping : shipping,
			shippingType : trim($('#shipping-method').val()),
            shippingData : ($('#same-data-for-shipping').attr('checked') ? '1' : (shippingData !== undefined ? json_encode(shippingData) : '0'))
        }),
        dataType: 'json',
        success: function(result){
            if (result.error) {
                $('#ajaxmsg').text(result.msg);
            } 
        }
    });
}

function generateQuote(emailSend)
{
    var quoteId = $('#quoteId-hidden').val();
    var urlwebsite = $('#wsurl-hidden').val();
    //get user mail text and internal message text
    var userMailText   = $('textarea#mailusertext').val();
    var intMessageText = $('textarea#intmsgtext').val();
    var disclaimer = trim($('#quote-disclaimer').val());
    var shipping = $('#shipping').val();

    if (!/^([0-9.]{1,10})$/.test(shipping)) {
        shipping = 0;
    }
    //show message on ajax start
    $('#ajaxmsg').ajaxStart(function(){
        $('#shipping').attr('readonly','readonly');
        $(this).text('Generating quote. Please wait...');
        $(this).show();
    })

    updateCart(false);
    updateQuoteData(quoteId);
    
    //send ajax request
    $.ajax({
        async: false,
        type : 'post',
        url : urlwebsite+'sys/backend_quote/generate/',
        data : {
            qid : quoteId,
            intMessage : intMessageText,
            usrMailText : userMailText,
            disclaimer : disclaimer,
            shipping : shipping,
            discount : trim($('#discount').val()),
            //shippingData : ($('#same-data-for-shipping').attr('checked') ? '1' : (shippingData !== undefined ? json_encode(shippingData) : '0')),
            emailSend: emailSend
        },
        dataType: 'json',
        success: function(result){
            if(result.error) {
                $('#ajaxmsg').text(result.msg);
                $('#shipping').removeAttr('readonly');
            }
            else {
                if (result.msg == 'success') {
                    $('#ajaxmsg').text('Quote generated. Mail sent to user.');
                }
                else if (result.msg == 'saved') {
                    $('#ajaxmsg').text('Quote generated and saved.');
                }
                
                //window.setTimeout("window.location.reload()", 3000);
                $('#ajaxmsg').click(function(){
                    window.location.reload();
                })
            }
        }
    });
}

function addProductForQuote()
{
    var urlWebsite = $('#wsurl-hidden').val();
    Sc.init({websiteurl : urlWebsite})
    Sc.idShoppingGroups = 'sc-groups';
    Sc.idShoppingProducts = 'sc-products';
    Sc.idShoppingBrands = 'sc-brands';
    Sc.forQuote = true;
    $.ajax({
        type : 'post',
        url : urlWebsite+'sys/backend_container/getgroupsandbrands/',
        success: function(data){
            result = eval('(' + data + ')');
            $('#sc-groups').html(result.groups);
            $('#sc-brands').html(result.brands);
            var contentReplaced =  replaceOnClick(result.products);
            $('#sc-products').html(contentReplaced);
            Sc.contentAllProducts = contentReplaced;
        }
    });
    //Sc.tabForContent();
    $('#sc-groupbrands').show();
}

function reCountTotalPrice()
{
	var shipping = $('#shipping').val();
    var discount = $('#discount').val();
	var taxRate	 = $('#discount-tax-rate').val();
	var taxRule	 = $('#discount-tax-rate').data('currentRule');
	var taxAmount = $('#current-tax-total').val();
	var subTotal = $('#current-sub-total').val();
	
	if (/^([0-9.]{1,})$/.test(shipping) && /^([0-9.]{1,})$/.test(discount)) {
        shipping = parseFloat(shipping);
        discount = parseFloat(discount);
		taxRate  = parseFloat(taxRule[taxRate])/100;
		subTotal = parseFloat(subTotal);
		taxAmount = parseFloat(taxAmount);
		var taxDiscount = discount - discount/(1+taxRate);
        var grandTotal = subTotal + shipping + taxAmount - discount;
		var newCurrentTax = taxAmount - taxDiscount;
		$('#current-tax-amount').html(newCurrentTax.toFixed(2));
        $('#grand-total').html(grandTotal.toFixed(2));
    } else {
        $('#grand-total').html($('#current-sub-total').val());
    }
}

function storeChangedParam($container, property, id, value){
    var data = $container.data(property);
    var done = false;
    data = ( null !== data && undefined !== data ? data : [] );
    for (i=0; i<data.length; i++ ) {
        if (data[i].id == id) {
            data[i].value = value;
            done = true;
        }
    }
    if (!done) {
        data.push( {id:id, value: value} )
    }
    $container.data(property, data)
}